package com.atguigu.edu.publisher.controller;

import com.alibaba.fastjson.JSON;
import com.atguigu.edu.publisher.beans.PlayChapterDate;
import com.atguigu.edu.publisher.mapper.PlayStatsMapper;
import com.atguigu.edu.publisher.service.PlayStatsService;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/play")
public class PlayStatsController {


    @Autowired
    PlayStatsService playStatsService;

    @RequestMapping("/chapter")
    public String getChapter(@RequestParam(value = "date" , defaultValue = "1") String date){
        if ("1".equals(date)){
            date = DateFormatUtils.format(new Date(), "yyyyMMdd");
        }

        List<PlayChapterDate> statsDate = playStatsService.getStatsDate(date);

        HashMap<String, Object> chapter = new HashMap<>();
        chapter.put("status",0);
        HashMap<String, Object> data = new HashMap<>();

        List<Object> columns = new ArrayList<>();
        columns.add(putHash("章节","chapterName"));
        columns.add(putHash("视频播放次数","playSum"));
        columns.add(putHash("累计播放时长","timeSum"));
        columns.add(putHash("观看人数","userSum"));
        columns.add(putHash("人均观看时长","avgTime"));
        data.put("columns", columns);

        ArrayList<Object> rows = new ArrayList<>();
        for (PlayChapterDate playChapterDate : statsDate) {
            HashMap<String, Object> hash = new HashMap<>();
            hash.put("chapterName", playChapterDate.getChapterName());
            hash.put("playSum",playChapterDate.getPlaySum());
            hash.put("timeSum",playChapterDate.getTimeSum());
            hash.put("userSum",playChapterDate.getUserSum());
            hash.put("avgTime",playChapterDate.getAvgTime());
            rows.add(hash);
        }
        data.put("rows", rows);
        chapter.put("data", data);

        return JSON.toJSONString(chapter);
    }

    private HashMap<String, String> putHash(String name, String id) {
        HashMap<String, String> hash = new HashMap<>();
        hash.put("name",name);
        hash.put("id",id);
        return hash;
    }

}
